import React from 'react';
import styles from './GoodsInput.css';

var GoodsInput = React.createClass({
  getInitialState() {
    let props=this.props
    this.updId = props.goods.updId
    return {}
  },
  updId: -1,
  componentDidUpdate() {
    // alert(123)
   let props=this.props
     let content=props.goods.content

    if (props.goods.updId != this.updId) {
      let goods = props.goods.content.filter(x => x.id == props.goods.updId)[0]
      this.setState({...goods})
      this.updId = props.goods.updId
    }
  },
  render(){
    // console.log(this.state)
    let props=this.props
    let formRef={}
    return (
      <div className={styles.normal}>
        <label htmlFor="isbn">isbn</label>
        <input type="text" id="isbn" ref={x=>formRef.isbn=x}
               value={this.state.isbn || ''} onChange={(e) => {
          this.setState({isbn: e.target.value})
        }}/>

        <label htmlFor="title">title</label>
        <input type="text" id="title" ref={x=>formRef.title=x}
               value={this.state.title || ''} onChange={(e) => {
          this.setState({title: e.target.value})
        }}/>
        <label htmlFor="prise">prise</label>
        <input type="text" id="prise" ref={x=>formRef.prise=x}
               value={this.state.prise || ''} onChange={(e) => {
          this.setState({prise: e.target.value})
        }}/>
        <button onClick={()=>{

          if (props.goods.updId == -1) {
          let isbn=formRef.isbn.value
          let title=formRef.title.value
          let prise=formRef.prise.value
          if (''===isbn.trim()){alert('请输入isbn')}
          if (''===title.trim()){alert('请输入title')}
          if (''===prise.trim()){alert('请输入prise')}
          props.dispatch({type:'goods/add',good:{isbn,title,prise}})
          this.setState({isbn:'', title:'', prise:''}),
            formRef.isbn.focus()
          }
          else {
            let id=props.goods.updId
            let isbn=formRef.isbn.value
            let title=formRef.title.value
            let prise=formRef.prise.value
            if (''===isbn.trim()){alert('请输入isbn')}
            if (''===title.trim()){alert('请输入title')}
            if (''===prise.trim()){alert('请输入prise')}
            props.dispatch({type: 'goods/upd', goods:{id,isbn,title,prise}})
            alert('更新成功。')
            this.setState({isbn:'', title:'', prise:''}),
              formRef.isbn.focus()
            props.goods.updId = -1
          }
        }}>
          {props.goods.updId == -1 ? '+' : 'U'}</button>
      </div>
    )
  },
})


export default GoodsInput
